package com.platformer.levels;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class Level {
	
	private TiledMap map;
	private OrthogonalTiledMapRenderer mapRenderer;
	private World world;
	
	
	public Level(World world) {
		map = new TmxMapLoader().load("data/tiledMapTest/level1.tmx");
		mapRenderer = new OrthogonalTiledMapRenderer(map, 1 / 16f);
		this.world = world;
		
		createTileObjects();
	}
	
	public void render(OrthographicCamera camera) {
		mapRenderer.setView(camera);
		mapRenderer.render();
	}
	
	private void createTileObjects() {
		TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
		for (int y = 0; y < layer.getHeight(); y++) {
			for (int x = 0; x < layer.getWidth(); x++) {
				Cell cell = layer.getCell(x, y);
				if (cell != null) {
					createStaticBox(x + 0.5f, y + 0.5f);
				}
			}
		}
	}
	
	private void createStaticBox(float x, float y) {
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = BodyType.StaticBody;
		bodyDef.position.set(x, y);

		Body body = world.createBody(bodyDef);

		PolygonShape polygonShape = new PolygonShape();
		polygonShape.setAsBox(0.5f, 0.5f);

		body.createFixture(polygonShape, 1);

		polygonShape.dispose();
	}
	
	public void dispose() {
		mapRenderer.dispose();
		map.dispose();
	}
}
